//
//  GGRouteMatcher.m
//  qqqqqq
//
//  Created by iOSer on 2017/3/2.
//  Copyright © 2017年 iOSer. All rights reserved.
//

#import "GGRouteMatcher.h"
#import "GGRegularExpression.h"
#import "GGMatchResult.h"

@interface GGRouteMatcher()
@property(nonatomic,copy) NSString *scheme;
@property(nonatomic,strong) GGRegularExpression *regexMatcher;
@end

@implementation GGRouteMatcher
+(instancetype)matcherWithRouteExpression:(NSString *)expression{
    return [[self alloc] initWithRouteExpression:expression];
}

-(instancetype)initWithRouteExpression:(NSString *)routeExpression{
    if (![routeExpression length]) {
        return nil;
    }
    
    if (self = [super init]) {
        NSArray *parts = [routeExpression componentsSeparatedByString:@"://"];
        _scheme = parts.count>1?[parts firstObject]:nil;
        _routeExpressionPattern = [parts lastObject];
        _regexMatcher = [GGRegularExpression expressionWithPattern:_routeExpressionPattern];
        _originalRouteExpression = routeExpression;
    }
    return self;
}

-(GGRouteRequest *)createRequestWithURL:(NSURL *)URL primitiveParameters:(NSDictionary *)primitiveParameters isJumpMethod:(JumpMethod)jumpMethod isShowNav:(BOOL)isShowNav NAVTitle:(NSString *)navTitle isNavAnimation:(BOOL)isNavAnimation targetCallBack:(void (^)(NSError *, id))targetCallBack{
    //取出URL地址和路径拼装
    NSString *urlString = [NSString stringWithFormat:@"%@%@",URL.host,URL.path];
    //如果初始化时取出的协议存在并且协议和当前协议不同 则返回空
    if (self.scheme.length && ![self.scheme isEqualToString:URL.scheme]) {
        return nil;
    }
    //通过自身的正则处理器判断是否匹配 返回一个匹配结果
    GGMatchResult *result = [self.regexMatcher matchResultForString:urlString];
    if (!result.isMatch) {
        return nil;
    }
    

    GGRouteRequest *request = [[GGRouteRequest alloc] initWithURL:URL routeExpression:self.routeExpressionPattern routePatameters:result.paramProperties  primitivePatameters:primitiveParameters isJumpMethod:jumpMethod isShowNav:isShowNav NAVTitle:navTitle isNavAnimation:isNavAnimation targetCallBack:targetCallBack];
    
    return request;
}
@end
